
const stripe = Stripe('pk_test_51MZoa8J65TIeSBouaBXmfypL14FiiFW1ea5bS9Q3x9Q1OZWEb1mZsUYjkIfrTpn0hG3xY0iKfxzfZBK2jLnSMHDW00X4VjOrig');

document.addEventListener('click', event => {
    makeProductPayment(event);
    addProductToCart(event);
    closeStandardNotification(event);
    makePaymentToShoppingCart(event);
})


function makePaymentToShoppingCart(event) {
    // Выполняем оплату корзины продуктов

    if (!event.target.closest('[data-buy-shopping-cart]')) return;
    event.preventDefault();

    const token = document.querySelector(
        '.buy-shopping-cart-form>input[name="csrfmiddlewaretoken"]'
    ).value;
    const url = document.location.origin + '/cart/?pay_for_order=true';
    const body = {'token': token}
    base.sendAjaxRequest('POST', url, body)
        .then(result => {
            const checkoutSessionId = result.checkout_session_id;
            return stripe.redirectToCheckout({ sessionId: checkoutSessionId });
        })
}

function closeStandardNotification(event) {
    // Закрываем стандартное оповещение

    if (!event.target.closest('[data-close-standard-notification]')) return;
    document.querySelector('.standard-notification').remove();
}


function makeProductPayment(event) {
    // Выполняем оплату продукта

    if (!event.target.closest('[data-buy-product]')) return;
    event.preventDefault();

    const [token, product_id] = base.get_basic_information_about_single_product()
    const url = document.location.origin + `/buy/${product_id}/?session_to_pay_for_product=true`;
    const body = {'token': token}
    base.sendAjaxRequest('POST', url, body)
        .then(result => {
            const checkoutSessionId = result.checkout_session_id;
            return stripe.redirectToCheckout({ sessionId: checkoutSessionId });
        })
}


function addProductToCart(event) {
    // Добавляем продукт в корзину

    if (!event.target.closest('[data-add-product-to-cart]')) return;
    event.preventDefault();

    const [token, product_id] = base.get_basic_information_about_single_product();
    const url = document.location.origin + '/cart/?add_product_to_cart=true';
    const body = {'token': token, 'product_id': product_id};
    base.sendAjaxRequest('POST', url, body)
        .then(result => {
            base.showNotification(result.message);
        })
}
